package classpath

import (
	"hi-jvm/util"
	"path/filepath"
)

type Classpath struct {
	BootClasspath Entry
	ExtClasspath Entry
	UserClasspath Entry
}

func Parse(jreOption, cpOption string) *Classpath{
	cp := &Classpath{}
	cp.parseAndExtClasspath(jreOption)
	cp.parseUserClasspath(cpOption)
	return cp
}

func (self *Classpath)ReadClass(className string) ([]byte, Entry, error) {
	className = className + ".class"
	if data, entry, err := self.BootClasspath.ReadClass(className); err == nil {
		return data, entry, err
	}

	if data, entry, err := self.ExtClasspath.ReadClass(className); err == nil {
		return data, entry, err
	}
	return self.UserClasspath.ReadClass(className)
}

func (self *Classpath)String() string {
	return self.UserClasspath.String()
}

func (self *Classpath)parseAndExtClasspath(jreOption string) {
	jreDir := util.GetJreDir(jreOption)

	// jre/lib/*
	jreLibPath := filepath.Join(jreDir, "lib", "*")
	self.BootClasspath = NewWidcardEntry(jreLibPath)

	// jre/lib/ext/
	jreExtPath := filepath.Join(jreDir, "lib", "ext", "*")
	self.ExtClasspath = NewWidcardEntry(jreExtPath)
}

func (self *Classpath)parseUserClasspath(cpOption string) {
	if "" == cpOption {
		cpOption = "."
	}

	self.UserClasspath = NewEntry(cpOption)
}
